$(function() {
  const api = 'http://api.zymk.cn/app_api/v3/';
  let userInfo = getCookie('user'),
    path = location.pathname,
    index = path.lastIndexOf('\/'),
    modifyflag = path.substring(index + 1, path.length);
  let { openid, type } = userInfo;
  let updateBtn = $('.updateBtn');
  if(modifyflag === 'username') {
    updateBtn.on('click', function() {
      let reg = new RegExp("^[\\w\\u4e00-\\u9fa5]+$");
      let val = $('#name').val();
      let action = 'nickname';
      if(reg.test(val)) {
        modifyFn(openid, type, action, val)
      } else {
        console.log('请输入正确的内容')
      }
    })
  } else if(modifyflag === 'sex') {
    let boy = $('.boy .ift-check');
    let girl = $('.girl .ift-check');
    if(userInfo.Usex == 1) {
      boy.show();
      girl.hide();
    } else {
      boy.hide();
      girl.show();
    }
    $('.chooseSex').on('click', 'div', function() {
      let flag = $(this).data('flag');
      let action = 'sex';
      if(flag === 'boy') {
        let val = 1;
        modifyFn(openid, type, action, val)
      } else {
        let val = 2
        modifyFn(openid, type, action, val)
      }
    })
  }


  function modifyFn(openid, type, action, val) {
    $.ajax({
      url: api + 'setuserinfo',
      data: {
        openid: openid,
        type: type,
        action: action,
        value: val
      },
      dataType: 'jsonp',
      jsonp: 'callback',
      success: function(res) {
        if(res.status === 0) {
          switch(modifyflag) {
            case 'username':
              userInfo.Uname = val;
              break;
            case 'sex':
              userInfo.Usex = val;
          }
          setCookie('user', JSON.stringify(userInfo), 365);
        } else {
          console.log(res.msg)
        }
      }
    })
  }
})